package com.wizardOther.Items;

import com.appclient.DaoInstanceEnum;
import com.carpark.ejb.Model.ClientsModel;
import com.wizardOther.OtherControlledScreen;
import com.wizardOther.OtherScreensController;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Modality;
import javafx.stage.Stage;
import popup.PopupController;

/**
 *
 * @author Sawior
 */
public class ClientMailController implements Initializable, OtherControlledScreen {

    private OtherScreensController myController;
    @FXML
    private Label counterText;
    @FXML
    private TextField filterField;
    @FXML
    private TableView<ClientsModel> clientTable;
    @FXML
    private TableColumn<ClientsModel, String> name;
    @FXML
    private TableColumn<ClientsModel, String> lastName;
    @FXML
    private TableColumn<ClientsModel, String> city;
    @FXML
    private TableColumn<ClientsModel, String> street;
    @FXML
    private TableColumn<ClientsModel, String> houseNr;
    @FXML
    private TableColumn<ClientsModel, String> localNr;
    private ObservableList<ClientsModel> masterData = FXCollections.observableArrayList();
    private ObservableList<ClientsModel> filteredData = FXCollections.observableArrayList();
    @FXML
    private Button send;
    @FXML
    private Button clear;
    @FXML
    private TextField topic;
    @FXML
    private HTMLEditor editor;

    public ClientMailController() {
        List<ClientsModel> data = DaoInstanceEnum.INSTANCE.getDao().getAllClients();
        for (ClientsModel client : data) {
            if (client.getEmail() != null) {
                if (!client.getEmail().isEmpty()) {
                    masterData.add(client);
                }
            }
        }

        filteredData.addAll(masterData);
        masterData.addListener(new ListChangeListener<ClientsModel>() {
            @Override
            public void onChanged(ListChangeListener.Change<? extends ClientsModel> change) {
                updateFilteredData();
            }
        });

    }

    @FXML
    public void sendMails(ActionEvent event) {
        if (event.getSource() == send) {
            if (editor.getHtmlText().isEmpty()) {
                createPopup("Nie wpisałeś tekstu wiadomości");
                this.editor.getStyleClass().add("textFieldWrong");
                return;
            }
            if (getSelectionList().isEmpty()) {
                createPopup("Nie wybrałeś żadnego odbiorcy wiadomości e-mail.");
                this.clientTable.getStyleClass().add("textFieldWrong");
                return;
            }
            if (topic.getText().isEmpty()) {
                createPopup("Nie podałeś tytułu wiadomości e-mail");
                this.topic.getStyleClass().add("textFieldWrong");
                return;
            }
            markAsGood();
            clearForm();
            createPopup("Operacja powiodła się. Wysłano maili: "+getSelectionList().size());
        }
    }


    private void markAsGood() {
        this.topic.getStyleClass().remove("textFieldWrong");
        this.editor.getStyleClass().remove("textFieldWrong");
        this.clientTable.getStyleClass().remove("textFieldWrong");
    }

    @FXML
    public void clearData(ActionEvent event) {
        if (event.getSource() == clear) {
            clearForm();
        }
    }

    private void clearForm() {
        editor.setHtmlText("");
        topic.setText("");
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        initialize();
    }

    @Override
    public void setScreenParent(OtherScreensController screenParent) {
        myController = screenParent;
    }

    @FXML
    private void initialize() {
        name.setCellValueFactory(
                new PropertyValueFactory<ClientsModel, String>("name"));
        lastName.setCellValueFactory(
                new PropertyValueFactory<ClientsModel, String>("lastName"));
        city.setCellValueFactory(
                new PropertyValueFactory<ClientsModel, String>("city"));
        street.setCellValueFactory(
                new PropertyValueFactory<ClientsModel, String>("street"));
        houseNr.setCellValueFactory(
                new PropertyValueFactory<ClientsModel, String>("houseNumber"));
        localNr.setCellValueFactory(
                new PropertyValueFactory<ClientsModel, String>("localNumber"));

        clientTable.setItems(filteredData);

        filterField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {
                updateFilteredData();
            }
        });
        clientTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        clientTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                int count = getSelectionList().size();
                String text = "Wybrano: " + getSelectionList().size();
                if (count > 1) {
                    text += " użytkowników";
                } else {
                    text += " użytkownika";
                }
                counterText.setText(text);
            }
        });
    }

    /**
     * Updates the filteredData to contain all data from the masterData that
     * matches the current filter.
     */
    private void updateFilteredData() {
        filteredData.clear();

        for (ClientsModel p : masterData) {
            if (matchesFilter(p)) {
                filteredData.add(p);
            }
        }

        // Must re-sort table after items changed
        reapplyTableSortOrder();
    }

    /**
     * Returns true if the person matches the current filter. Lower/Upper case
     * is ignored.
     *
     * @param client
     * @return
     */
    private boolean matchesFilter(ClientsModel client) {
        String filterString = filterField.getText();
        if (filterString == null || filterString.isEmpty()) {
            return true;
        }
        String lowerCaseFilterString = filterString.toLowerCase();

        if (client.getName().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (client.getLastName().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (client.getCity().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (client.getStreet().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        Integer localNumber = client.getLocalNumber();
        if (localNumber != null) {
            if (localNumber.toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
                return true;
            }
        }
        if (client.getHouseNumber().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (client.getZipCode().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (client.getPhone().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }

        return false;
    }

    private void reapplyTableSortOrder() {
        ArrayList<TableColumn<ClientsModel, ?>> sortOrder = new ArrayList<>(clientTable.getSortOrder());
        clientTable.getSortOrder().clear();
        clientTable.getSortOrder().addAll(sortOrder);
    }

    private ObservableList<ClientsModel> getSelectionList() {
        return clientTable.getSelectionModel().getSelectedItems();
    }

    private void createPopup(String text) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("popup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Uwaga!");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);
            
            PopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            controller.setPopupText(text);
            dialogStage.showAndWait();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
